import {
	getList,
	getDetail,
	newBlog,
	updateBlog,
	delBlog
} from '../controller/blog.js'
import { SuccessModel, ErrorModel } from '../model/res-model.js'

// 统一的登录验证函数
const loginCheck = (req) => {
	if (!req.session.username) {
		return new ErrorModel('尚未登录')
	}
}

const handleBlogRouter = async (req, res) => {
	// 设置返回格式 JSON
	res.setHeader('Content-type', 'application/json')

	const method = req.method
	const id = req.query.id

	// 获取博客列表
	if (method === 'GET' && req.path === '/api/blog/list') {
		const author = req.query.author
		const keyword = req.query.keyword
		const listData = await getList(author, keyword)
		return new SuccessModel(listData)
	}

	// 获取博客详情
	if (method === 'GET' && req.path === '/api/blog/detail') {
		const data = await getDetail(id)
		return new SuccessModel(data)
	}

	// 新建博客
	if (method === 'POST' && req.path === '/api/blog/new') {
		const loginCheckResult = loginCheck(req)
		if (loginCheckResult) {
			// 未登录
			return loginCheck
		}

		req.body.author = req.session.username
		const data = await newBlog(req.body)
		return new SuccessModel(data)
	}

	// 更新博客
	if (method === 'POST' && req.path === '/api/blog/update') {
		const loginCheckResult = loginCheck(req)
		if (loginCheckResult) {
			// 未登录
			return loginCheck
		}

		const result = await updateBlog(id, req.body)
		if (result) {
			return new SuccessModel()
		} else {
			return new ErrorModel('更新博客失败')
		}
	}

	// 删除博客
	if (method === 'POST' && req.path === '/api/blog/del') {
		const loginCheckResult = loginCheck(req)
		if (loginCheckResult) {
			// 未登录
			return loginCheck
		}

		const author = req.session.username
		const result = await delBlog(id, author)
		if (result) {
			return new SuccessModel()
		} else {
			return new ErrorModel('删除博客失败')
		}
	}
}

export default handleBlogRouter
